/*
 * @Author: 薛严 348352046@qq.com
 * @Date: 2023-04-14 14:27:33
 * @LastEditors: 薛严 348352046@qq.com
 * @LastEditTime: 2023-04-18 09:59:09
 * @FilePath: /applet-server/index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: 薛严 348352046@qq.com
 * @Date: 2023-04-14 14:27:33
 * @LastEditors: 薛严 348352046@qq.com
 * @LastEditTime: 2023-04-17 16:51:04
 * @FilePath: /applet-server/index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 *
 */
const express = require("express");
const bodyParser = require("body-parser");
const reuqest = require("request");
const crypto = require('crypto');
const WXBizDataCrypt = require('./WXBizDataCrypt')

const app = express();
app.use(bodyParser.json());
const wx = {
  // 小程序配置
  appId: "wx74b443b94cb6b01d",
  srcret: "74f7b855d959c82d5f50c26bcba78787",
};
const db = {
  // 需要保存的信息
  session: {},
  user: {},
};

app.post("/login", (req, res) => {
  console.log("login-code", req.body);
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wx.appId}&secret=${wx.srcret}&js_code=${req.body.code}&grant_type=authorization_code`;
  reuqest(url, (error, response, body) => {
    console.log("body", body);
    const session = JSON.parse(body);
    const token = "Login_Token" + new Date().getTime();
    db.session[token] = session;
    if (!db.user[session.openId]) {
      db.user[session.openId] = { credit: 100 };
    }
    res.json({ token: token });
  });
});

app.get("/checklogin", (req, res) => {
  const session = db.session[req.query.token];
  res.json({ code: 0, isLogin: session !== undefined });
});

app.get("/credit", (req, res) => {
  const session = db.session[req.query.token];
  if (session && db.user[session.openId]) {
    res.json({ code: 0, credit: db.user[session.openId].credit });
  } else {
    res.json({ code: 1, msg: "用户不存在,或未登录." });
  }
});
app.post('/userinfo', (req, res)=> {
  const session = db.session[req.query.token]
  if(session) {
    const pc = new WXBizDataCrypt(wx.appId, session.session.session_key)
  }
})
app.get('/getlivekey', (req, res)=>{
  res.json({code: 0,  key: '0ebcf25ed9f04bd6af080b7ccdf605fe'})
})
app.listen(2810, () => {
  console.log("====================================");
  console.log("server running at http://127.0.0.1:2810");
  console.log("====================================");
});
